package com.shuaiche.yeguan.ui.report;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.SCApplication;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.config.SCUserInfoConfig;
import com.shuaiche.yeguan.model.SCAccessAuthResponse;
import com.shuaiche.yeguan.model.SCCarCategoryListModel;
import com.shuaiche.yeguan.model.SCCarCategoryModel;
import com.shuaiche.yeguan.model.SCMaintenanceRecordListResponse;
import com.shuaiche.yeguan.model.SCMaintenanceRecordResponse;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.net.oss.MultiImagesUploadManager;
import com.shuaiche.yeguan.ui.common.WebviewActivity;
import com.shuaiche.yeguan.util.GlideUtil;
import com.shuaiche.yeguan.util.StringUtils;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.views.photopicker.PhotoPickerActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 上传维保报告
 */
public class SCMaintenanceReportActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUESR_FOR_MAITENANCE_UPLOAD = 101;
    RelativeLayout rl_back;
    /**有vin 显示*/
     View svContent;

    /**无vin 显示*/
     View vNoVinCode;

    SCMatchingRecordsAdapter adapter;
    ImageView imgLogo;
    TextView tvCarName;
    TextView tvVin;
    RecyclerView rvMaintenance;
    Button btnUpload;
    Button btnUploadVin;
    Button btnSureSelect;
    TextView tvTip;

    private int pageNo = 1; //当前页
    private int pageSize = 4;
    private boolean isCanLoadMore = true;
    private String carId;
    private String vin;     //vin码
    StringBuffer sb = new StringBuffer();
    private String logo = "";
    Bundle bundle = new Bundle();
    private View footerView;

    private SCMaintenanceRecordListResponse recordResponse;
    private final static int REQUEST_CODE=101;

    private String reportPcUrl;
    private String reportPic;
    private String reportPdf;
    private String page;
    private ActivityResultLauncher<Intent> reportResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        );

        setContentView(R.layout.activity_scmaintenance_report);

        initViews();
    }

    private void initViews() {
        initFindViews();
        carId = getIntent().getStringExtra("carId");
        vin = getIntent().getStringExtra("vin");
        page = getIntent().getStringExtra("page");
        reportPcUrl = getIntent().getStringExtra("reportPcUrl");
        reportPdf = getIntent().getStringExtra("reportPdf");
        reportPic = getIntent().getStringExtra("reportPic");
        tvVin.setText(!StringUtils.isEmpty(vin) ? vin : "-");
        if (StringUtils.isEmpty(vin)) {
            svContent.setVisibility(View.GONE);
            vNoVinCode.setVisibility(View.VISIBLE);
        } else {
            svContent.setVisibility(View.VISIBLE);
            vNoVinCode.setVisibility(View.GONE);
            setVinView();
        }


        reportResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK){
                            handleReportActivityResultData(result);
                        }
                    }
                });
    }

    private void handleReportActivityResultData(ActivityResult result) {
        Intent data = result.getData();

        finish();
    }

    private void initFindViews() {
        rl_back = findViewById(R.id.rl_back);
        svContent = findViewById(R.id.svContent);
        vNoVinCode = findViewById(R.id.vNoVinCode);
        imgLogo = findViewById(R.id.img_logo);
        tvCarName = findViewById(R.id.tv_car_name);
        tvVin = findViewById(R.id.tv_vin);
        rvMaintenance = findViewById(R.id.rv_maintenance);
        btnUpload = findViewById(R.id.btn_upload);
        btnUploadVin = findViewById(R.id.btnUploadVin);
        btnSureSelect = findViewById(R.id.btn_sure_select);
        tvTip = findViewById(R.id.tv_tip);

        rl_back.setOnClickListener(this);
        btnUpload.setOnClickListener(this);
        btnSureSelect.setOnClickListener(this);
        btnUploadVin.setOnClickListener(this);
    }

    /**
     * 设置视图
     */
    private void setVinView() {
        footerView = View.inflate(this, R.layout.layout_foolt_weibao, null);
        adapter = new SCMatchingRecordsAdapter(this, new ArrayList<SCMaintenanceRecordResponse>());
        //设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置布局管理器
        rvMaintenance.setLayoutManager(layoutManager);
        //设置增加或删除条目的动画
        rvMaintenance.setItemAnimator(new DefaultItemAnimator());
        rvMaintenance.setAdapter(adapter);
        getCarMaintenanceRecordList(pageSize);
        getCarByVin();
        footerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter.removeFooterView(footerView);
                pageSize = 200;
                getCarMaintenanceRecordList(pageSize);
            }
        });
        adapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                Bundle bundleWeb = new Bundle();
                if (!StringUtils.isEmpty(adapter.getItem(i).getReportPdf())){
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("netUrl",adapter.getItem(i).getReportPdf());
                    bundle1.putString("vin", adapter.getItem(i).getVcode());
                    bundle1.putString("carName", adapter.getItem(i).getCarName());
                    bundle1.putString("imgLogo", adapter.getItem(i).getBrandLogo());
//                    startFragment(SCMaintenanceReportFragment.this, SCPDFPreviewFragment.class, bundle1);
                    return;
                } else if (!StringUtils.isEmpty(adapter.getItem(i).getReportWapUrl())) {
                    bundleWeb.putString("url", adapter.getItem(i).getReportWapUrl());
                } else {
//                    String ImgUrl = SCImageUrlUtils.appendImageUrl(adapter.getItem(i).getReportPic());
//                    bundleWeb.putString("url", ImgUrl);
//                    bundleWeb.putString("title", "报告详情");
                    bundleWeb.putString("url", SCAppConfig.URL_MAINTENANCE_DETAIL +
                            "?maintenanceId=" +adapter.getItem(i).getId());
                }
                bundleWeb.putBoolean("ChaType", true);
                bundleWeb.putString("vin", adapter.getItem(i).getVcode());
                bundleWeb.putString("carName", adapter.getItem(i).getCarName());
                bundleWeb.putString("imgLogo", adapter.getItem(i).getBrandLogo());

                Intent webIntent = new Intent(SCMaintenanceReportActivity.this, WebviewActivity.class);
                webIntent.putExtras(bundleWeb);
                startActivity(webIntent);
            }
        });

        tvVin.setText(!StringUtils.isEmpty(vin) ? vin : "-");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            /**
             * 上传点击按钮
             */
            case R.id.btn_upload:
                bundle.putString("vin", vin);
                bundle.putString("carId", carId);
                if (adapter != null && adapter.getItemCount() > 0) {
                    bundle.putSerializable("maintenance", adapter.getItem(0));
                }
                bundle.putString("reportPcUrl", reportPcUrl);
                bundle.putString("reportPdf", reportPdf);
                bundle.putString("reportPic", reportPic);
                bundle.putString("page", page);

                Intent reportIntent = new Intent(this, UploadMaintenanceReportActivity.class);
                reportIntent.putExtras(bundle);

//                startActivity(reportIntent);

                reportResultLauncher.launch(reportIntent);

//                startFragmentForResult(SCMaintenanceReportFragment.this,
//                        SCCarEditUploadMaintenance2Fragment.class, bundle,
//                        REQUESR_FOR_MAITENANCE_UPLOAD );
                break;
            /**
             * 查询点击按钮跳转维保查询
             */
            case R.id.btn_sure_select:
//                bundle.putString("vin", vin);
//                startFragmentForResult(SCMaintenanceReportFragment.this, SCPayMaintenanceOrderFragment.class, bundle,REQUEST_CODE);

//                Intent weibaoIntent = new Intent();
//                weibaoIntent.setClass(getCurrContext(), MyReactActivity.class);
//                weibaoIntent.putExtra("typepage","1007");
//
//                HashMap<String,String> params = new HashMap<>();
//                params.put("vin",vin);
//                weibaoIntent.putExtra("paramsMap", params);
//
//                startActivity(weibaoIntent);

                ReactContext reactContext = SCApplication.getApplication().getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
                if (reactContext == null) {
                    return;
                }
                WritableMap event = Arguments.createMap();

                event.putString("page",page);
                event.putString("vcode",vin);
                reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("foursQuery", event);

                finish();
                break;

            case R.id.btnUploadVin:
                /**上传VIN码*/
                final SCEditVinDialogFragment fragment = new SCEditVinDialogFragment();
                fragment.setConfirmListener(new SCEditVinDialogFragment.ConfirmListener() {
                    @Override
                    public void confirm(String content) {
                        if (content.length() ==17) {
                            content.toUpperCase();
                            vin = content;
                            setVinView();
//                            if (carId != null && carId != 0) {
////                                insertVcode();
//                            }
                            svContent.setVisibility(View.VISIBLE);
                            vNoVinCode.setVisibility(View.GONE);
                            fragment.dismiss();
                        } else {
                            ToastShowUtils.showTipToast("请输入正确的VIN码");
                        }
                    }

                    @Override
                    public void cancel() {
                    }
                });

                fragment.show(getSupportFragmentManager(), "SCEditVinDialogFragment");


                break;
        }
    }


    /**
     * 通过vin码获取维保记录
     */
    private void getCarMaintenanceRecordList(int pageSize) {

        JSONObject paramJson = new JSONObject();
        try {
            paramJson.put("vcode",vin);
            paramJson.put("pageSize",pageSize);
            paramJson.put("pageNo",pageNo);
            paramJson.put("merchantId", SCUserInfoConfig.getUserinfo().getMerchantId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HttpHelper.getInstance().appendUrl(HttpUrl.GET_MAINTENANCE_RECORD_LIST)
                .addJsonParam(paramJson.toString())
                .jsonPost(new HttpCallBack<SCMaintenanceRecordListResponse>(this) {
                    @Override
                    public void onSuccessed(SCMaintenanceRecordListResponse result) {
                        recordResponse = (SCMaintenanceRecordListResponse) result.getData();
                        if (recordResponse == null || recordResponse.getResultList() == null || recordResponse.getResultList().size() == 0) {
                            return;
                        }
                        if (recordResponse.getTotalSize() > 0) {
                            tvTip.setText("帅车联盟已为您匹配了" + recordResponse.getTotalSize() + "条维保记录");
                        } else {
                            tvTip.setText("帅车联盟暂未匹配到维保记录");
                        }

                        adapter.setNewData(recordResponse.getResultList());
                        if (recordResponse.getTotalSize() > 4 && pageSize == 4) {
                            adapter.addFooterView(footerView);
                        } else {
                            adapter.removeFooterView(footerView);
                        }
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {

                    }
                });
    }


    /**
     * 获取车辆信息
     */
    private void getCarByVin() {
        Map<String,Object> maps = new HashMap<>();
        maps.put("vin",vin);
        HttpHelper.getInstance().appendUrl(HttpUrl.GET_CAR_BY_VIN)
                .addGetParam(maps)
                .get(new HttpCallBack<SCCarCategoryListModel>(this) {
                    @Override
                    public void onSuccessed(SCCarCategoryListModel result) {
                        List<SCCarCategoryModel> listModel = (List<SCCarCategoryModel>) result.getData();
                        if (listModel == null || listModel.size() == 0) {
                        } else {
                            for (int i = 0; i < listModel.size(); i++) {
                                if ("1".equals(listModel.get(i).getLevel())) {
                                    sb.append(listModel.get(i).getName());
                                    sb.append("-");
                                    logo = listModel.get(i).getLogo();
                                }
                                if ("3".equals(listModel.get(i).getLevel())) {
                                    if (!StringUtils.isEmpty(listModel.get(i).getLogo())) {
                                        logo = listModel.get(i).getLogo();
                                    }
                                    sb.append(listModel.get(i).getName());
                                    sb.append("-");
                                }
                                if ("5".equals(listModel.get(i).getLevel())) {
                                    if (!StringUtils.isEmpty(listModel.get(i).getLogo())) {
                                        logo = listModel.get(i).getLogo();
                                    }
                                    sb.append(listModel.get(i).getName());
                                    sb.append("-");
                                }
                                GlideUtil.loadRoundImg(SCMaintenanceReportActivity.this, logo, imgLogo, R.mipmap.pic_default_company_logo);
                            }
                            if (sb.indexOf("-", sb.length() - 1) > 0) {
                                sb.deleteCharAt(sb.length() - 1);
                            }
                            tvCarName.setText(!StringUtils.isEmpty(sb.toString()) ? sb.toString() : "-");

                        }
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {

                    }
                });
    }

}